<?php
/**
 * Created by PhpStorm.
 * User: 小蛮哼哼哼
 * Email: 243194993@qq.com
 * Date: 2021/11/17
 * Time: 16:57
 * motto: 现在的努力是为了小时候吹过的牛逼！
 */

declare(strict_types=1);

namespace app\common\business;

use app\common\lib\Show;
use app\common\lib\Status;
use app\common\model\mysql\GrabSheet;
use app\common\model\mysql\Order as ModelObj;
use app\common\validate\Order as ValObj;
use think\Exception;
use think\facade\Log;
use think\helper\Str;

class PlaceOrder extends Base
{
    protected $valObj = null;
    protected $modelObj = null;

    public function __construct()
    {
        $this->valObj = new ValObj();
        $this->modelObj = new ModelObj();
    }

    /**
     * @param array $data
     * @return false|float[]
     * @throws Exception
     */
    public function add(array $data = [])
    {
        $param = [
            "relname" => $data['name'],
            "sex" => $data['sex'],
            "mobile" => $data['mobile'],
            "wx" => $data['wx'],
            "express_order" => $data['kd'],
            "weight" => $data['weight'],
            "xian" => $data['qdxz'],
            "description" => $data['desc'],
            "is_lou" => $data['isLot'],
            "start_address" => $data['qu'],
            "end_address" => $data['address_name'],
            "address_lat" => $data['address_lat'],
            "address_lng" => $data['address_lng'],
            "address_detail" => $data['address_detail'],
            "idCard" => $data['idCard'],
            "idCard_z" => $data['idCardImg'][0]['param'] ?? '',
            "idCard_f" => $data['idCardImg'][1]['param'] ?? '',
            "idM" => $data['idNum'],
            "idPath" => $data['idCardImgFile'][0]['url'] ?? '',
            "mark" => strip_tags($data['mark']),
            "money" => $data['money'],
            "openid" => $data['openid'],
            "qu_lat" => $data['qu_lat'],
            "qu_lng" => $data['qu_lng'],
            "address_qu_info" => $data['address_qu_info'],
            "qcode" => $data['qcode'],
            "is_gui" => $data['is_gui']

        ];
        $param['order_id'] = date('YmdHis') . Str::random(6, 1);
//        dump($param);exit();
        $this->isValidateAdd($param);
        if ($param['end_address'] == "选择地址") {
            throw new Exception("请选择送货地址");
        }
        //添加
        $res = $this->modelObj->save($param);
        if ($res) {
            return [
                "order_id" => $param['order_id']
            ];
        } else {
            return false;
        }
    }

    /**
     * @param $limit
     * @param $page
     * @return array
     * @throws Exception
     */
    public function getOrderList($limit, $page, array $where = []): array
    {
        try {
            $order = $this->modelObj->getOrderList($limit, $page, $where);
        } catch (\Exception $e) {
            throw new Exception("查询失败");
        }
        return $order;

    }

    public function getOrderByGrabId(int $id = 0, string $openid = '')
    {
        if (empty($openid) || $id == 0) {
            throw new Exception("内部错误");
        }
        try {
            $order = $this->getBaseById($id);
        } catch (\Exception $e) {
            return Show::json_show(Status::mini_error, "服务异常!");
        }
        if ($order['payStatus'] != 1) {
            return Show::json_show(Status::mini_error, "订单状态异常");
        }
        if ($order['state'] != 1) {
            return Show::json_show(Status::mini_error, "订单已被抢");
        }

        $this->modelObj->startTrans();
        try {
            $this->modelObj->updateByData($id, [
                "state" => 2
            ]);
            $insert_data = [
                "order_id" => $id,
                "openid" => $openid,
                "money" => $order['money']
            ];
            (new GrabSheet())->insertAdd($insert_data);
            $this->modelObj->commit();
        } catch (\Exception $e) {

            $this->modelObj->rollback();
            throw new Exception("内部错误");
        }
        return true;
    }

    /**
     * 根据订单号查询订单
     * @param string $order_id
     * @return ModelObj|array|\think\Model|null
     * @throws Exception
     */
    public function getOrderByOrderId(string $order_id = '')
    {
        try {
            $order = $this->modelObj->getOrderByOrderId($order_id);
        } catch (\Exception $e) {
            throw new Exception("查询失败");
        }
        return $order;
    }

    /**
     * @param int $type
     * @param int $limit
     * @param int $page
     * @param string $openid
     * @return array
     * @throws Exception
     */
    public function getUserOrder(int $type = 0, int $limit = 10, int $page = 1, string $openid = ''): array
    {
        $map = [];
        $map[] = [
            ['openid', '=', $openid]
        ];
        switch ($type) {
            case 1:   //待付款
                $map[] = [
                    ['state', '=', 1],
                    ['payStatus', '=', 0]
                ];
                break;
            case 2:  //待接单
                $map[] = [
                    ['state', '=', 1],
                    ['payStatus', '=', 1]
                ];
                break;
            case 3: //待取货
                $map[] = [
                    ['state', '=', 2],
                    ['payStatus', '=', 1]
                ];
                break;
            case 4: //已完成
                $map[] = [
                    ['state', '=', 3],
                    ['payStatus', '=', 1]
                ];
                break;
            case 5:
                $map[] = [
                    ['state', '=', 4],
                    ['payStatus', 'in', [1, 2]]
                ];
                break;
            case 99:  //全部订单
                break;
            default:
                throw new Exception("发生错误");
                break;
        }
        try {
            $lists = $this->modelObj->getUserOrder($map, $limit, $page, '*,id as auth_id');
        } catch (\Exception $e) {
            Log::error($e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            throw new Exception("查询失败");
        }
        return $lists;
    }

    /**
     * @param $id
     * @return mixed
     * @throws Exception
     */
    public function setPayment($id)
    {
        try {
            $order = $this->getBaseById($id);
        } catch (\Exception $e) {
            throw new Exception("查询错误");
        }
        if (!$order) {
            throw new Exception("订单不存在");
        }
        if ($order['payStatus'] != 0) {
            throw new Exception("订单已经支付");
        }
        return $order;
    }

    public function getPlaceOrderByCount(array $where = [], string $field = '*')
    {
        try {
            $result = $this->modelObj->getPlaceOrderByCount($where, $field);
        } catch (\Exception $e) {
            throw new Exception("查询失败");
        }
        return $result;
    }

    /**
     * @param string $openid
     * @return ModelObj|array|\think\Model|null
     * @throws Exception
     */
    public function getLastOrder(string $openid = '')
    {
        try {
            $res = $this->modelObj->field('*,sex as set_sex')
                ->where('openid', $openid)
                ->order('id desc')
                ->find();
        } catch (\Exception $e) {
            throw new Exception("查询错误");
        }
        return $res;
    }

    public function setOrderByTimeState()
    {
        try {
            $order = $this->modelObj->getOrderByStateTime();
        } catch (\Exception $e) {
            throw new Exception("发生错误");
        }
        $ids = array_column($order, 'id');
        try {
            $result = $this->modelObj->updateIdsByState($ids);
        } catch (\Exception $e) {
            throw new Exception("发生错误");
        }
        return $result;
    }

    /**
     * @param int $id
     * @param string $openid
     * @return bool
     * @throws Exception
     */
    public function setStateByOrder(int $id = 0, string $openid = '')
    {
        //查询是否存在
        try {
            $order = $this->getBaseById($id,'*,order_id as ret_id');
        } catch (\Exception $e) {
            throw new Exception("内部错误");
        }
        if (!$order) {
            throw new Exception("订单不存在");
        }
        $this->modelObj->startTrans();
        try {
            $this->modelObj->updateByData($order['id'], [
                "state" => 4,
                "update_time" => time()
            ]);
            (new \app\common\model\mysql\Money())
                ->where('order_id', $order['id'])
                ->where('openid', $openid)
                ->update([
                    "state" => 1,
                    "update_time" => time()
                ]);
            $this->modelObj->commit();
        } catch (\Exception $e) {
            Log::error($e->getMessage() . " " . $e->getFile() . " " . $e->getLine());
            $this->modelObj->rollback();
            throw new Exception("内部错误");
        }
        return true;

    }
}